package com.sjb.cp.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjb.cp.exception.BusinessException;
import com.sjb.cp.exception.ErrorCode;
import com.sjb.cp.exception.ThrowUtils;
import com.sjb.cp.manager.auth.StpKit;
import com.sjb.cp.model.dto.UserTokenDto;
import com.sjb.cp.model.enums.UserRoleEnum;
import com.sjb.cp.model.po.User;
import com.sjb.cp.model.request.user.UserQueryRequest;
import com.sjb.cp.model.vo.UserLoginVo;
import com.sjb.cp.model.vo.UserVo;
import com.sjb.cp.service.UserService;
import com.sjb.cp.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.sjb.cp.model.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author dell
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-12-10 09:14:48
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword,String userType) {

        if (StrUtil.hasBlank(userAccount, checkPassword,checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length() < 4 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户昵称过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次输入的密码不一致");
        }

        // 检查是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        Long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号重复");
        }

        String encryptPassword = getEncryptPassword(userPassword);
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName("无名");
        user.setUserRole(Objects.requireNonNull(UserRoleEnum.getEnumByText(userType)).getValue());
        boolean save = this.save(user);

        if (!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"注册失败，系统异常");
        }

        return user.getId();
    }

    @Override
    public UserLoginVo userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StrUtil.hasBlank(userAccount,userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length() < 4 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码错误");
        }

        String encryptPassword = getEncryptPassword(userPassword);
        // 检查用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount)
                .eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        // 记录用户登录态 到sa-token
        StpKit.SPACE.login(user);
        StpKit.SPACE.getSession().set(USER_LOGIN_STATE,user);
        return this.getLoginUserVo(user);
    }

    @Override
    public String getEncryptPassword(String userPassword) {
        final String salt = "cloud-picture";
        return DigestUtils.md5DigestAsHex((salt + userPassword).getBytes());
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 判断是否已经登录
        Object object = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) object;

        if (currentUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        }

        Long id = currentUser.getId();
        currentUser = this.getById(id);

        if (currentUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        }
        return currentUser;
    }

    @Override
    public UserLoginVo getLoginUserVo(User user) {
        UserLoginVo userLoginVo = new UserLoginVo();
        userLoginVo.setUserRole(user.getUserRole());
        userLoginVo.setUserAccount(user.getUserAccount());
        userLoginVo.setUserName(user.getUserName());
        return userLoginVo;
    }

    @Override
    public boolean logOut(HttpServletRequest request) {
        Object object = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) object;
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户未登录");
        }

        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取单个登录用户信息
     * @param user
     * @return
     */
    @Override
    public UserVo getUserVo(User user) {
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"用户不存在");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        return userVo;
    }

    /**
     * 批量获取用户信息
     * @param users
     * @return
     */
    @Override
    public List<UserVo> getUserVoList(List<User> users) {
        if (users == null){
            return new ArrayList<>();
        }
        return users.stream().map(this::getUserVo).collect(Collectors.toList());
    }

    /**
     * 用户查询封装统一的queryWrapper
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getRole();
        String sortField = userQueryRequest.getSortFiled();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        //queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("descend"), sortField);
        return queryWrapper;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }
}




